using System;
using System.Collections.Generic;
using System.Text;
using NBusiness.CodeDom;

namespace NBusiness.Templates
{
    public static class Dependency
    {
        /// <summary>
        /// Finds the first template associated with the given entity that implements the specified contract.
        /// </summary>
        /// <param name="contract">The contract this entity must implement for the contract to be valid.</param>
        /// <param name="entity">The entity whose templates must implement the specified contract.</param>
        /// <returns>An instance </returns>
        public static T GetContract<T>(Entity entity) where T : IContract
        {
            T contractInstance = default(T);

            foreach(EntityTemplate template in entity.As)
            {
                Type type = Type.GetType(template.Type.ToString());
                if (type != null && typeof(T).IsAssignableFrom(type))
                {
                    contractInstance = (T)Activator.CreateInstance(type);
                    break;
                }
            }

            return contractInstance;
        }
    }
}
